<template>
	<view class="order-list">
		<!-- 遍历订单的详情内容 -->
		<view v-for="(order, index) in orders" :key="index" class="order-item">
			<!-- 订单头部信息：时间和状态 -->
			<view class="order-header">
				<text class="order-date">{{ order.createdAt }}</text>
				<text class="order-status">{{ order.statusText }}</text>
			</view>
			<!-- 订单详情 -->
			<view class="order-content" v-for="(item, idx) in order.items" :key="idx">
				<image :src="loadUrl + item.image" mode="aspectFill" class="order-image"></image>
				<view class="order-info">
					<text class="order-name">{{ item.title }}</text>
					<text class="order-price">价格: ¥{{ item.price / 100 }}</text>
				</view>
			</view>
			<!-- 订单底部：总金额 -->
			<view class="order-footer">
				<text class="order-total">订单总金额: ¥{{ order.totalFee / 100 }}</text>
				<button :class="['order-button', { 'primary': order.buttonType === 'primary' }]"
					@click="handleButtonClick(order)">
					{{ order.buttonText }}
				</button>
			</view>
		</view>

		<!-- 改进的评价弹窗 -->
		<view v-if="showReviewPopup" class="popup-overlay">
			<view class="popup-content">
				<text class="popup-title">提交评论</text>
				<view class="popup-rating">
					<text class="rating-label">评分:</text>
					<view class="star-rating">
						<text v-for="star in 5" :key="star" :class="['star', { 'active': star <= reviewData.rating }]"
							@click="setRating(star)">
							★
						</text>
					</view>
				</view>
				<view class="popup-review">
					<text class="review-label">评论内容:</text>
					<textarea v-model="reviewData.reviewText" placeholder="请输入评论内容" class="review-textarea"></textarea>
				</view>
				<view class="popup-buttons">
					<button @click="submitReview" class="submit-btn">提交</button>
					<button @click="closePopup" class="cancel-btn">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loadUrl: this.$loadUrl,
				orders: [],
				showReviewPopup: false,
				reviewData: {
					rating: 0,
					reviewText: '',
					orderId: null
				}
			};
		},
		mounted() {
			this.fetchOrders();
		},
		methods: {
			fetchOrders() {
				this.$service({
					url: '/orders/category?type=3',
					method: 'GET',
				}).then(res => {
					if (res.code === 0) {
						this.orders = res.data.map(order => ({
							createdAt: order.createdAt,
							status: order.status,
							statusText: this.getStatusText(order.status),
							items: order.details.map(item => ({
								title: item.title,
								image: item.image,
								price: item.price
							})),
							orderId: order.id,
							totalFee: order.totalFee,
							buttonText: this.getButtonText(order.status),
							buttonType: this.getButtonType(order.status)
						}));
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			getOrderDetails(orderId) {
				this.$service({
					url: `/orders/unpaid/${orderId}`,
					method: 'GET'
				}).then(res => {
					if (res.code === 0) {
						const orderData = res.data;
						const orderInfo = {
							id: orderData.id,
							createdAt: orderData.createdAt,
							products: orderData.items.map(item => ({
								title: item.title,
								spec: item.spec,
								price: item.price,
								number: item.number,
								image: item.image,
							}))
						};
						setTimeout(() => {
							uni.$emit('orderId', orderInfo.id)
						}, 300)
						uni.navigateTo({
							url: `/pages/payment/payment?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
						});
					}
				}).catch(error => {
					console.error('获取订单详情失败', error);
				});
			},
			openReviewPopup(orderId) {
				this.reviewData.orderId = orderId;
				this.showReviewPopup = true;
			},
			closePopup() {
				this.showReviewPopup = false;
				this.reviewData.rating = 1;
				this.reviewData.reviewText = '';
			},
			setRating(rating) {
				this.reviewData.rating = rating;
			},
			submitReview() {
				const {
					rating,
					reviewText,
					orderId
				} = this.reviewData;
				if (rating < 1 || !reviewText.trim()) {
					uni.showToast({
						title: '请填写评分和评论内容',
						icon: 'none'
					});
					return;
				}

				this.$service({
					url: '/reviews',
					method: 'POST',
					data: {
						orderId,
						rating,
						reviewText
					}
				}).then(res => {
					if (res.code === 0) {
						this.updateOrderStatus(orderId); // 更新订单状态为已评价
						this.closePopup(); // 关闭弹窗
						uni.showToast({
							title: '评价提交成功',
							icon: 'success'
						});
					} else {
						throw new Error(res.message || '提交评论失败');
					}
				}).catch(error => {
					console.error('提交评论失败', error);
					uni.showToast({
						title: error.message || '提交评论失败，请稍后重试',
						icon: 'none'
					});
				});
			},
			updateOrderStatus(orderId) {
				this.orders = this.orders.map(order => {
					if (order.orderId === orderId) {
						order.status = 4; // 设置状态为已评价
						order.statusText = '已评价'; // 按钮显示已评价
						order.buttonText = '已评价'; // 改变按钮文字
						order.buttonType = 'default'; // 改变按钮为灰色样式
					}
					return order;
				});
			},
			getStatusText(status) {
				switch (status) {
					case -1:
						return '已取消';
					case 0:
						return '待支付';
					case 1:
						return '已支付';
					case 3:
						return '待评价';
					default:
						return '未知状态';
				}
			},
			getButtonText(status) {
				switch (status) {
					case -1:
						return '再次购买';
					case 0:
						return '去支付';
					case 1:
						return '已支付';
					case 3:
						return '去评价';
					default:
						return '';
				}
			},
			getButtonType(status) {
				switch (status) {
					case -1:
						return 'default';
					case 0:
						return 'primary';
					case 1:
						return 'default';
					case 3:
						return 'primary';
					default:
						return '';
				}
			},
			handleButtonClick(order) {
				if (order.buttonText === '去支付') {
					this.getOrderDetails(order.orderId);
				} else if (order.buttonText === '去评价') {
					this.openReviewPopup(order.orderId);
				} else {
					console.log('再次购买', order.orderId);
				}
			}
		}
	};
</script>

<style scoped>
	.order-button.default {
		background-color: #ccc;
		/* 灰色背景 */
		color: #fff;
		/* 白色文字 */
		border: none;
	}

	.order-list {
		background-color: #f5f5f5;
		padding: 20rpx;
	}

	.order-item {
		background-color: #ffffff;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.order-date,
	.order-status {
		color: #999;
		font-size: 24rpx;
	}

	.order-content {
		display: flex;
		margin-bottom: 20rpx;
	}

	.order-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
		border-radius: 10rpx;
	}

	.order-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.order-name {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
	}

	.order-price {
		font-size: 24rpx;
		color: #999;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.order-total {
		font-size: 24rpx;
		color: #333;
	}

	.order-button {
		font-size: 24rpx;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		background-color: #ffffff;
		color: #333;
		border: 1rpx solid #ccc;
	}

	.order-button.primary {
		background-color: #ff6600;
		color: #fff;
		border: none;
	}

	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-content {
		background-color: #fff;
		padding: 40rpx;
		border-radius: 20rpx;
		width: 80%;
		max-width: 600rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.popup-rating,
	.popup-review {
		margin-bottom: 30rpx;
	}

	.rating-label,
	.review-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.star-rating {
		display: flex;
		justify-content: center;
		margin-top: 10rpx;
	}

	.star {
		font-size: 50rpx;
		color: #ddd;
		margin: 0 5rpx;
	}

	.star.active {
		color: #ffb800;
	}

	.review-textarea {
		width: 100%;
		height: 150rpx;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
	}

	.submit-btn,
	.cancel-btn {
		width: 45%;
		padding: 20rpx 0;
		border-radius: 40rpx;
		font-size: 28rpx;
		color: #fff;
		border: none;
		text-align: center;
	}

	.submit-btn {
		background-color: #ff6600;
	}

	.cancel-btn {
		background-color: #999;
	}
</style>